# 8 字符串转换整数
# https://leetcode.cn/problems/string-to-integer-atoi/description/
# Date: 2024/10/28
import re


def myAtoi(s: str) -> int:
    """我的解法"""
    INT_MIN, INT_MAX = -2 ** 31, 2 ** 31 - 1
    # 头部是空格
    while s[:1] == ' ':
        s = s[1:]

    n, neg = len(s), False  # neg 表示是否是负数
    rs, result = "", 0  # rs表示result的string格式
    for i in range(n):
        if i == 0 and (s[i] == '-' or s[i] == '+'):
            if s[i] == '-':
                neg = True
            continue
        if re.match(r'\d', s[i]) is not None:  # 检查每个字符是否是数字
            rs += s[i]
        else:
            break

    if len(rs) == 0:
        return 0
    else:
        if neg:
            result = -int(rs)
        else:
            result = int(rs)

    if result > INT_MAX:
        return INT_MAX
    if result < INT_MIN:
        return INT_MIN

    return result


class Automaton:
    """为了避免类似复杂流程已经较多条件的情况, 可以考虑使用自动机(Automaton)
    自动机假设每个时刻有一个当前状态 state, 每次我们从字符串中输入一个字符c, 并根据c来转移到下一个状态state'.
    这样我们就需要建立一个覆盖所有情况的从 state -> state' 的映射表格
    |           | ' '   | +/-    | number    | other |
    |start      | start | signed | in_number | end   |
    |signed     | end   | end    | in_number | end   |
    |in_number  | end   | end    | in_number | end   |
    |end        | end   | end    | end       | end   |
    """

    def __init__(self):
        self.state = 'start'
        self.sign = 1
        self.ans = 0
        self.table = {
            'start': ['start', 'signed', 'in_number', 'end'],
            'signed': ['end', 'end', 'in_number', 'end'],
            'in_number': ['end', 'end', 'in_number', 'end'],
            'end': ['end', 'end', 'end', 'end'],
        }

    INT_MAX = 2 ** 31 - 1
    INT_MIN = -2 ** 31

    def _get_col(self, c):
        if c.isspace():
            return 0
        if c == '+' or c == '-':
            return 1
        if c.isdigit():
            return 2
        return 3

    def get(self, c):
        self.state = self.table[self.state][self._get_col(c)]
        if self.state == 'in_number':
            self.ans = self.ans * 10 + int(c)
            self.ans = min(self.ans, self.INT_MAX) if self.sign == 1 else min(self.ans, -self.INT_MIN)
        elif self.state == 'signed':
            self.sign = 1 if c == '+' else -1


def myAtoi_auto(str: str) -> int:
    automaton = Automaton()
    for c in str:
        automaton.get(c)
    return automaton.sign * automaton.ans


if __name__ == '__main__':
    print(myAtoi("42"))
    print(myAtoi("   -042"))
    print(myAtoi("1337c0d3"))
    print(myAtoi("0-1"))
    print(myAtoi("words and 987"))
    print(myAtoi_auto("99999999999999"))
    print(myAtoi_auto("-91283472332"))  # -2147483648
